package com.csdj.springboottest.service;

import com.csdj.springboottest.entity.Config;
import com.csdj.springboottest.mapper.ConfigMapper;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * author:cloud
 * date:2021/4/23 0023
 **/

@Service
@CacheConfig(cacheManager = "redisCacheManager", cacheNames = "configCache")
public class ConfigService {
    @Resource
    private ConfigMapper configMapper;

    @Cacheable(key="#type",unless="#result == null")
    public List<Config> getByType(String type){
      return configMapper.findByType(type);
    }


    /**
     * 先从缓存中查询，
     * @param type
     * @param key
     * @return
     */
    @Cacheable(key="#type+'-'+#key",unless="#result == null")
    public Config get(String type,String key){
        return configMapper.findConfig(type,key);
    }

    /**
     * 更新成功则删除缓存
     * @param config
     * @return
     */
    @CacheEvict(key="#config.type+'-'+#config.key",condition = "#result == true")
    @Caching(evict = {@CacheEvict(key = "#config.type",condition = "#result == true")})
    public boolean update(Config config){
        return configMapper.update(config)>0;
    }


    /**
     * 保存成功后，添加到缓存中，并清除缓存集合
     * @param config
     * @return
     */
    @Caching(
            put = {@CachePut(key = "#config.type+'-'+#config.key",unless = "#result == null")},
            evict = {@CacheEvict(key = "#config.type", allEntries = true)}
    )
    public Config insert(Config config){
        config.setStatus((byte)1);
        if(configMapper.insert(config)>0){
            return config;
        }
        return null;
    }
}
